#include "Texture.hpp"
#include "lodepng.h"

Typhoon::Texture::Texture() {
	width = 0;
	height = 0;
	texture = 0;
}

Typhoon::Texture::~Texture() {
	Free();
}

int Typhoon::Texture::GetWidth() {
	return width;
}

int Typhoon::Texture::GetHeight() {
	return height;
}

GLuint Typhoon::Texture::GetHandle() {
	return texture;
}

void Typhoon::Texture::LoadFromPng(std::string filename) {

	std::vector<unsigned char> buffer;
		
	LodePNG::loadFile(buffer, filename);

	if (buffer.empty()) return;

	LodePNG::Decoder decoder;

	std::vector<unsigned char> image;
	decoder.decode(image, buffer);

	width = (int)decoder.getWidth();
	height =  (int)decoder.getHeight();

	

	glGenTextures(1, &texture);
	glBindTexture(GL_TEXTURE_2D, texture);
	
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	//glTexParameteri(GL_TEXTURE_2D, GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);

	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, &image[0]);
	
}

void Typhoon::Texture::Free() {
	if (texture) {
		glDeleteTextures(0, &texture);
		texture = 0;
	}
}

